/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package staplers;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.NamingContainer;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;

/**
 *
 * @author robert
 */
@ManagedBean
@SessionScoped
public class CategoryCTRL {
    DBHelper helper;
    Category category;
    List categoryList;
    List<Attribute> attributeList;
    List<Item> itemList;
    int noDefineCategoryAttributes = 0;
    private DataModel categoryModel;
    private boolean doUpdate;

    /** Creates a new instance of CategoryCTRL */
    public CategoryCTRL() {
        helper = ((UserCTRL)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("userCTRL")).getHelper();
        category = new Category();
    }

    public List<Item> getItemList() {
        return itemList;
    }

    
    public int getNoDefineCategoryAttributes() {
        return noDefineCategoryAttributes;
    }
    
    public String addDefineCategoryAttribute()
    {
        noDefineCategoryAttributes++;
        if (doUpdate)
            return "EditCategory";
        return "DefineCategory";
    }
    
    public String removeDefineCategoryAttribute()
    {
        if (noDefineCategoryAttributes > 0)
            noDefineCategoryAttributes--;
        if (doUpdate)
            return "EditCategory";
        return "DefineCategory";
    }
    
    public Category getCategory()
    {
        return category;
    }
    
    public String defineNewCategoryPrep()
    {
        category = new Category();
        doUpdate = false;
        this.noDefineCategoryAttributes = 0;
        return "DefineCategory";
    }
    
    public String defineNewCategory()
    {
        
        FacesContext ctx = FacesContext.getCurrentInstance();

        Map<String, String> request = ctx.getExternalContext().getRequestParameterMap();
        
        String _catList = request.get("newCategoryForm" + NamingContainer.SEPARATOR_CHAR + "catList");
        String _catList2 = request.get("newCategoryForm" + NamingContainer.SEPARATOR_CHAR + "catList2");
        if (!_catList.equalsIgnoreCase("null"))
            category.setCategoryByCategoryOf(helper.getCategoryById(Integer.parseInt(_catList)));
        if (!_catList2.equalsIgnoreCase("null"))
            category.setCategoryBySuitableFor(helper.getCategoryById(Integer.parseInt(_catList2)));    
        
        int retValue = helper.defineNewCategory(category);
        if (retValue == -1) {
            category = null;
            ((UserCTRL)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("userCTRL")).setErrMsg("Uh oh... something went wrong");
            return "DefineCategory";
        }
        
        Set<Attribute> attributes = new HashSet<Attribute>(0);
           
        if (noDefineCategoryAttributes>0){
            for (int i=1;i<=noDefineCategoryAttributes;i++)
            {
                String attributeName = request.get("newCategoryForm" + NamingContainer.SEPARATOR_CHAR + "attribute"+i);
                Attribute attribute = new Attribute(category,attributeName);
                attributes.add(attribute);
            }
            retValue = helper.defineNewAttributes(attributes);
            if (retValue == -1) {
                category = null;
                ((UserCTRL)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("userCTRL")).setErrMsg("Uh oh... something went wrong");
                
                return "DefineCategory";
            }
            category.setAttributes(attributes);
        }
        
        categoryList = null;  
        ((UserCTRL)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("userCTRL")).setErrMsg("New category added!");
        return "AdminHome";
    }
    
    public String updateCategory()
    {
        FacesContext ctx = FacesContext.getCurrentInstance();

        Map<String, String> request = ctx.getExternalContext().getRequestParameterMap();
        
        String _catList = request.get("newCategoryForm" + NamingContainer.SEPARATOR_CHAR + "catList");
        String _catList2 = request.get("newCategoryForm" + NamingContainer.SEPARATOR_CHAR + "catList2");
        if (!_catList.equalsIgnoreCase("null")&&!_catList.equalsIgnoreCase("-1"))
            category.setCategoryByCategoryOf(helper.getCategoryById(Integer.parseInt(_catList)));
        if (!_catList2.equalsIgnoreCase("null")&&!_catList2.equalsIgnoreCase("-1"))
            category.setCategoryBySuitableFor(helper.getCategoryById(Integer.parseInt(_catList2)));
        Iterator<Attribute> iter = category.getAttributes().iterator();
        while (iter.hasNext())
        {
            Attribute attribute = iter.next();
            if (attribute.isSelected())
                helper.deleteAttribute(attribute);
        }
        helper.updateCategory(category);
        
        Set<Attribute> attributes = new HashSet<Attribute>(0);
        if (noDefineCategoryAttributes>0){
            for (int i=1;i<=noDefineCategoryAttributes;i++)
            {
                String attributeName = request.get("newCategoryForm" + NamingContainer.SEPARATOR_CHAR + "attribute"+i);
                Attribute attribute = new Attribute(category,attributeName);
                attributes.add(attribute);
            }
            helper.defineNewAttributes(attributes);
            
            itemList = getItemsByCategory(new ArrayList<Item>(), category);
            
            Iterator<Item> iter2 = itemList.iterator();
            while (iter2.hasNext())
            {
                Item item = iter2.next();
                Set<AttributeValue> attVal = new HashSet<AttributeValue>();
                for (Attribute att : attributes)
                    attVal.add(new AttributeValue(att,item,""));
                item.setAttributeValues(attVal);
            }
        }
        else
        {
            if (itemList != null)
                itemList.clear();
        }
            
            
        if (itemList != null && !itemList.isEmpty())
        {
            return "UpdateAttributeFieldsAfterEdit";
        }
        categoryList = null;  
        categoryModel = null;
        this.noDefineCategoryAttributes = 0;
        
        return "EditCategories";
    }
    
    public String updateAttributeFieldsAfterEdit()
    {
        for (Item item : itemList)
        {
            helper.defineNewAttributeValues(item.getAttributeValues());
        }
        return "EditCategories";
    }
    
    public List getCategoryList()
    {
        if (categoryList == null)
        {
            categoryList = getCategoriesByParent(null,0);
        }
        return categoryList;
    }
    
    public List getCategoriesByParent(Category categoryOf,int level)
    {
        List<Category> list = new ArrayList<Category>();
        List<Category> tempList = helper.getCategoryByCategoryOf(categoryOf);
        Iterator<Category> iter = tempList.iterator();
        while (iter.hasNext())
        {
            Category category = iter.next();
            if (category.getLevel().length()==0)
                for (int i=0;i<level;i++)
                    category.setLevel(category.getLevel()+"--");
            
            list.add(category);
            list.addAll(getCategoriesByParent(category,level+1));
        }
        return list;
    }
   
    public DataModel getCategoryModel()
    {
        if (categoryModel == null)
            categoryModel = new ListDataModel(getCategoryList());
        return categoryModel;
    }
    
    
    public List getAttributeList()
    {
        if (attributeList == null)
            attributeList = helper.getAttributeList();
        return attributeList;
    }

    public String editCategoriesPrep()
    {
        this.categoryList = null;
        this.categoryModel = null;
        this.noDefineCategoryAttributes = 0;
        return "EditCategories";
    }
    
    public String deleteCategory()
    {
        helper.deleteCategory((Category)categoryModel.getRowData());
        ((UserCTRL)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("userCTRL")).setErrMsg("Category deleted");
        categoryList = null;
        categoryModel = null;
        return "EditCategories";
    }
    
    public String selectCategoryForEditing()
    {
        category = (Category)categoryModel.getRowData();
        doUpdate = true;
        return "EditCategory";
    }

    private List<Item> getItemsByCategory(ArrayList<Item> list, Category cat) {
        list.addAll(helper.getItemsByCategory(cat));
        Category cat2 = helper.getCategoryById(cat.getId());
        for (Category category : cat2.getCategoriesForCategoryOf())
        {
            getItemsByCategory(list,category);
        }
        return list;
    }

    void resetCategory() {
        category = new Category();
    }
    
}
